package com.jiedeng.controller.index;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.jiedeng.controller.Rst;
import com.jiedeng.model.Person;
import com.jiedeng.model.PersonDetails;
import com.jiedeng.util.ForwardConstants;
import com.jiedeng.util.SessionUtil;
import com.jiedeng.util.httpclient.HttpClientHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 人员管理
 *
 * @author zhouyb
 */
@Controller
@Scope("prototype")
@RequestMapping("/personManage")
public class PersonManageController {
    @Value("${config.http.client.url}")
    public String url;
    @Value("${config.prefix}")
    public String downUrl;
    @Autowired
    CommonComponent commonComponent;
    /**
     * 人员管理首页
     *
     * @param model
     * @param request
     * @return
     * @paramojectId
     */
    @RequestMapping(value = "/personManageUI", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String taskManageUI(Model model, String projectId, HttpServletRequest request) {
        model.addAttribute("ctx", request.getContextPath());
        try {
            //用户
            model.addAttribute("personName", SessionUtil.getUserNameSession());
            //单位
            model.addAttribute("corpName", SessionUtil.getUserCorpNameSession());
            //model.addAttribute("projectId", projectId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/person/personHome";
    }

    /**
     * 人员列表
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/personList", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String personList(@RequestParam(defaultValue = "1") String page, @RequestParam(defaultValue = "10") String pageSize, Model model, HttpServletRequest request) {
        model.addAttribute("ctx", request.getContextPath());
        try {
            Rst rst = commonComponent.checkModuleRule("1010100");
            if(!"OK".equals(rst.getMsg())){
                return ForwardConstants.REDIRECT + "/jurisdictionBlank";
            }
            model.addAttribute("ctx", request.getContextPath());
            Map map = new HashMap();
            map.put("page", page);
            map.put("pageSize", pageSize);
            Person person = (Person) SessionUtil.getUserSession();
            String corpId = person.getCorpId() + "";
            map.put("corpId", corpId);
            String ret = HttpClientHelper.postRequest2(url + "/person/personCountList", map, "utf-8", "");
            String ret2 = HttpClientHelper.postRequest2(url + "/person/personCountNum", map, "utf-8", "");
            List<PersonDetails> personArrayList = new ArrayList<>();
            if (ret != null) {
                personArrayList = JSON.parseObject(ret.trim(), new TypeReference<List<PersonDetails>>() {
                });
            }
            for (PersonDetails personDetails : personArrayList) {

            }
            int count = Integer.parseInt(ret2);
            //路径
            model.addAttribute("downUrl", downUrl);
            model.addAttribute("count", count);
            model.addAttribute("maxPage", count / 10);
            model.addAttribute("page", page);
            model.addAttribute("pageSize", pageSize);
            //model.addAttribute("query", query);
            model.addAttribute("nowBegin", Integer.parseInt(pageSize) * (Integer.parseInt(page) - 1) + 1);
            model.addAttribute("nowEnd", Integer.parseInt(pageSize) * (Integer.parseInt(page) - 1) + personArrayList.size());
            model.addAttribute("PersonArrayList", personArrayList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/person/personList";
    }

    /**
     * 跳转添加用户
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/personAdd", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String personAdd(Model model, HttpServletRequest request) {
        model.addAttribute("ctx", request.getContextPath());
        try {
            Rst rst = commonComponent.checkModuleRule("1010200");
            if(!"OK".equals(rst.getMsg())){
                return ForwardConstants.REDIRECT + "/jurisdictionBlank";
            }
            //用户
            model.addAttribute("dataUrl", url);
            model.addAttribute("personName", SessionUtil.getUserNameSession());
            //单位
            model.addAttribute("corpName", SessionUtil.getUserCorpNameSession());
            model.addAttribute("corpId", ((Person) SessionUtil.getUserSession()).getCorpId());
            //model.addAttribute("projectId", projectId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/person/personAdd";
    }

    /**
     * 跳转用户修改
     *
     * @param personId
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/personEdit", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String personEdit(String personId, Model model, HttpServletRequest request) {
        model.addAttribute("ctx", request.getContextPath());
        try {
            model.addAttribute("ctx", request.getContextPath());
            Map map = new HashMap();
            model.addAttribute("dataUrl", url);
            map.put("personId", personId);
            model.addAttribute("corpId", ((Person) SessionUtil.getUserSession()).getCorpId());
            //String ret = HttpClientHelper.postRequest2(url + "/person/personEdit", map, "utf-8", "");
            String ret = HttpClientHelper.postRequest2(url + "/person/findPersonById", map, "utf-8", "");
            //PersonDetails personDetails = new PersonDetails();
            Person person = new Person();
            if (ret != null) {
               /* List<PersonDetails> personDetailsList  = JSON.parseObject(ret.trim(), new TypeReference<List<PersonDetails>>() {
                });
                if(personDetailsList!=null&&personDetailsList.size()>0){
                    personDetails=personDetailsList.get(0);
                }*/
                person = JSON.parseObject(ret.trim(), new TypeReference<Person>() {
                });
                if (person.isLock()) {
                    person.setWhetherLock("1");
                } else {
                    person.setWhetherLock("0");
                }
            }
            model.addAttribute("personDetails", person);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/person/personEdit";
    }

    /**
     * 新增用户
     *
     * @param startTime
     * @param endTime
     * @param addTime
     * @return
     */
    @ResponseBody
    @RequestMapping("/addPerson")
    public String addPerson(String startTime, String endTime, String addTime) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("name", SessionUtil.getPara("name"));
        map.put("loginid", SessionUtil.getPara("loginid"));
        map.put("password", SessionUtil.getPara("password"));
        map.put("phone", SessionUtil.getPara("phone"));
        map.put("isLock", SessionUtil.getPara("isLock"));
        map.put("postId", SessionUtil.getPara("postId"));
        map.put("corpId", ((Person) SessionUtil.getUserSession()).getCorpId() + "");
        if (StringUtils.isEmpty(startTime)) {
            startTime = addTime;
        }
        map.put("startTime", startTime);
        //map.put("addTime", addTime);
        if (!StringUtils.isEmpty(endTime)) {
            map.put("endTime", endTime);
        }
        try {
            String ret = HttpClientHelper.postRequest2(url + "/person/addPersonEntity", map, "utf-8", "");
            Rst rst = JSON.parseObject(ret.trim(), new TypeReference<Rst>() {
            });
            int code = rst.getResultCode();
            if (code == 0) {
                return ForwardConstants.SUCCESS;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ForwardConstants.ERROR;
    }

    /**
     * 修改用户
     *
     * @param startTime
     * @param endTime
     * @param addTime
     * @return
     */
    @ResponseBody
    @RequestMapping("/editPerson")
    public String editPerson(String startTime, String endTime, String addTime) {
        Map<String, String> map = new HashMap<String, String>();
        //map.put("name", SessionUtil.getPara("name"));
        map.put("loginid", SessionUtil.getPara("loginid"));
        map.put("password", SessionUtil.getPara("password"));
        map.put("phone", SessionUtil.getPara("phone"));
        map.put("isLock", SessionUtil.getPara("isLock"));
        map.put("personId", SessionUtil.getPara("personId"));
        map.put("postId", SessionUtil.getPara("postId"));
        //map.put("corpId", ((Person) SessionUtil.getUserSession()).getCorpId() + "");
        if (StringUtils.isEmpty(startTime)) {
            startTime = addTime;
        }
        map.put("startTime", startTime);
        //map.put("addTime", addTime);
        if (!StringUtils.isEmpty(endTime)) {
            map.put("endTime", endTime);
        }
        try {
            String ret = HttpClientHelper.postRequest2(url + "/person/editPersonEntity", map, "utf-8", "");
            Rst rst = JSON.parseObject(ret.trim(), new TypeReference<Rst>() {
            });
            int code = rst.getResultCode();
            if (code == 0) {
                return ForwardConstants.SUCCESS;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ForwardConstants.ERROR;
    }

    /**
     * 删除
     *
     * @param personId
     * @return
     */
    @ResponseBody
    @RequestMapping("/deletePerson")
    public String deletePerson(String personId) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("id", personId);
        try {
            HttpClientHelper.postRequest2(url + "/corp/person/delete", map, "utf-8", "");
            return ForwardConstants.SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ForwardConstants.ERROR;
    }

    /**
     * 权限校验
     *
     * @param byname
     * @return
     */
    @ResponseBody
    @RequestMapping("checkModuleRule")
    public Rst checkModuleRule(String byname) {
        Rst rst = commonComponent.checkModuleRule(byname);
        return rst;
    }
}
